/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.common.emailandsms;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Service
public class SendEmail {

    private static Logger logger = LoggerFactory.getLogger(SendEmail.class);
    /**
     * 邮件发送人
     */
    public static final String MAIL_FROM = "*************.com";
    /**
     * mail server
     */
    public static final String MAIL_HOST = "************";
    /**
     * 用户名
     */
    public static final String MAIL_USERNAME = "********";
    /**
     * 密码
     */
    public static final String MAIL_PASSWORD = "********";

    public static boolean simpleMailSend(String[] to, String text, String subject) {
        try {
            JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
            // 设定mail server
            senderImpl.setHost(MAIL_HOST);
            // 建立邮件消息
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            // 设置收件人，寄件人 用数组发送多个邮件
            // String[] array = new String[] {"sun111@163.com","sun222@sohu.com"};
            // mailMessage.setTo(array);
            mailMessage.setTo(to);
            //邮件发送人
            mailMessage.setFrom(MAIL_FROM);
            // 邮件标题
            mailMessage.setSubject(subject);
            // 邮件内容
            mailMessage.setText(text);
            //设置发送邮箱的username
            senderImpl.setUsername(MAIL_USERNAME);
            //设置发送邮箱的password
            senderImpl.setPassword(MAIL_PASSWORD);
            Properties prop = new Properties();
            prop.put("mail.smtp.auth", "true"); // 将这个参数设为true，让服务器进行认证,认证用户名和密码是否正确
            prop.put("mail.smtp.timeout", "25000");  //超时时间
            senderImpl.setJavaMailProperties(prop);
            // 发送邮件
            senderImpl.send(mailMessage);
            logger.debug("给" + Arrays.toString(to) + "邮件发送成功.");
            return true;
        } catch (MailException e) {
            logger.debug(e.getMessage());
        }
        return false;
    }

    public static boolean complexMailSend(List<String> to, String text, String subject, String url, InputStream[] inputStreams) {
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", MAIL_HOST);   // 指定SMTP服务器
            props.put("mail.smtp.auth", "true"); // 指定是否需要SMTP验证
            Session session = Session.getDefaultInstance(props);
            session.setDebug(false);
            MimeMessage message = new MimeMessage(session);
            //指定发送人
            message.setFrom(new InternetAddress(MAIL_FROM));
            //指定接收人
            if (null == to && to.size() <= 0) {
                return false;
            }
            for (String recierver : to) {
                if(StringUtils.isNotEmpty(recierver))
                     message.addRecipient(Message.RecipientType.TO, new InternetAddress(recierver));
            }
            //指定抄送人
            //设置标题
//            message.setSubject(new String(subject.getBytes("utf-8"),"utf-8"));
            message.setSubject(subject);
            message.addHeader("charset", "UTF-8");

            /*添加正文内容*/
            //一个Multipart对象包含一个或多个bodypart对象，组成邮件正文
            Multipart multipart = new MimeMultipart();

            MimeBodyPart contentPart = new MimeBodyPart();
            StringBuilder builder = new StringBuilder(text);
            if (StringUtils.isNotEmpty(url))
                builder.append("<a href='").append(url).append("'>点击查看详情</a>");
            contentPart.setText(builder.toString(), "UTF-8");
            contentPart.setHeader("Content-Type", "text/html; charset=UTF-8");
            multipart.addBodyPart(contentPart);

            /*添加附件*/
            if (inputStreams != null && inputStreams.length > 0) {
                int i = 0;
                for (InputStream is : inputStreams) {
                    MimeBodyPart fileBody = new MimeBodyPart();
                    DataSource source = new ByteArrayDataSource(is, "application/msexcel");
                    fileBody.setDataHandler(new DataHandler(source));
                    // 中文乱码问题
                    fileBody.setFileName(MimeUtility.encodeText("附件" + i));
                    multipart.addBodyPart(fileBody);
                    i++;
                }
            }
            message.setContent(multipart);
            message.setSentDate(new Date());
            message.saveChanges();
            if(message.getAllRecipients()!=null&&message.getAllRecipients().length>0){
                Transport transport = session.getTransport("smtp");
                transport.connect(MAIL_HOST, MAIL_USERNAME, MAIL_PASSWORD);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
                logger.info(Calendar.getInstance().getTime() + "给" + to.toArray().toString() + "邮件发送成功");
            }
            return true;
        } catch (MailException e) {
            logger.debug(e.getMessage());
        } catch (AddressException e) {
            logger.error(e.getMessage(),e);
        } catch (MessagingException e) {
            logger.error(e.getMessage(),e);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(),e);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
        return false;
    }

 }
